<template>
  <div class="dt-chat-groups">
    <div class="dt-groups-title">
      <span>项目群列表</span>
      <!-- <el-dropdown trigger="click" placement="bottom-start" @command="addGroupMenu">
        <span class="el-dropdown-link">
          <i class="el-icon-plus"></i>
        </span>
        <el-dropdown-menu slot="dropdown" class="dt-caht-addGroup">
          <el-dropdown-item command='1'>单一群聊</el-dropdown-item>
          <el-dropdown-item command='2'>高级群聊</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
    </div>
    <div class="dt-groups-list" ref="scrollChat">
      <div class="dt-groups-loading" v-if="loading.groupList"><i class="el-icon-loading"></i> <span>加载中，请稍后</span></div>
      <!-- <div class="dt-list-items" v-for="item in GroupList" :key="item.groupId" v-else>
        <div :class="['dt-list-item', { on: query.groupId == item.groupId }]" @click="goGroupChat(item)">
          <img :src="messTypeUrl[item.noticeType]" alt="" />
          <div class="dt-item-des">
            <div class="dt-des-chatname">
              <span>{{ item.groupName }}</span>
              <i>{{ item.createTimestamp | filterTimeStamp }}</i>
            </div>
            <div class="dt-des-chattip">
              <div class="dt-des-markdup" v-html="item.shortMessage"></div>
              <el-badge v-if="item.unreadCount != 0" :value="item.unreadCount" :max="99" class="item"></el-badge>
            </div>
          </div>
        </div>
        <div class="dt-list-gj-content" v-else>
          <div class="dt-list-item-gj" @click="showTree(item)">
            <img :src="messTypeUrl[item.noticeType]" alt="图像的描述">
            <div class="dt-list-item-gj-name">{{item.groupName}}</div>
            <div class="dt-list-item-gj-unreadCount">
              <el-badge v-if="item.rootUnreadCount!=0" :value="item.rootUnreadCount" :max="99" class="item"></el-badge>
            </div>
          </div>
          <el-tree :data="item.children" :props="defaultProps" @node-click="handleNodeClick" :default-expand-all="true" v-show="item.isShowTree"
            :expand-on-click-node="false" node-key="groupId" :ref="item.groupId">
            <div class="custom-tree-node" slot-scope="{ node, data }" :disabled="isNodeDisabled(data)">
              <span>{{ node.label }} </span>
              <div class="dt-list-item-gj-unreadCount">
          
                <el-badge v-if="data.unreadCount!=0" :value="data.unreadCount" :max="99" class="item"></el-badge>
              </div>
            </div>
          </el-tree>
        </div>
      </div> -->
      <div v-else>
        <div class="dt-list-items" v-for="(item, index) in GroupListTop" :key="item.groupId" :ref="item.groupId + '-' + index">
          <div
            :class="['dt-list-item', { on: query.groupId == item.groupId }]"
            @click="goGroupChat(item)"
            @contextmenu.prevent.stop="rightToTop($event, item, index)"
          >
            <img :src="messTypeUrl[item.noticeType]" alt="图像的描述" />
            <img src="/skb/img/ic_zd16.png" alt="图像的描述" width="16px" height="16px" class="dt-list-item-topicon" />
            <div class="dt-item-des">
              <div class="dt-des-chatname">
                <span>{{ item.groupName }}</span>
                <i>{{ item.createTimestamp | filterTimeStamp }}</i>
              </div>
              <div class="dt-des-chattip">
                <div class="dt-des-markdup" v-html="getemojiText(item.shortMessage)"></div>
                <el-badge v-if="item.unreadCount != 0" :value="item.unreadCount" :max="99" class="item"></el-badge>
              </div>
            </div>
            <div class="contextMenu" v-show="item.isShowMenu && item.noticeType != 2 && item.isDel != 1">
              <div @click="pinToTop($event, item)">取消置顶</div>
              <!-- <div @click="enableDoNotDisturb($event,item)">消息免打扰</div> -->
            </div>
          </div>
        </div>
        <div class="dt-list-items" v-for="(item, index) in GroupListBottom" :key="item.groupId" :ref="item.groupId + '-' + index">
          <div
            :class="['dt-list-item', { on: query.groupId == item.groupId }]"
            @click="goGroupChat(item)"
            @contextmenu.prevent.stop="rightToTop($event, item, index)"
          >
            <img :src="messTypeUrl[item.noticeType]" alt="图像的描述" />
            <div class="dt-item-des">
              <div class="dt-des-chatname">
                <span>{{ item.groupName }}</span>
                <i>{{ item.createTimestamp | filterTimeStamp }}</i>
              </div>
              <div class="dt-des-chattip">
                <div class="dt-des-markdup" v-html="getemojiText(item.shortMessage)"></div>
                <el-badge v-if="item.unreadCount != 0" :value="item.unreadCount" :max="99" class="item"></el-badge>
              </div>
            </div>
            <div class="contextMenu" v-show="item.isShowMenu && item.noticeType != 2 && item.isDel != 1">
              <div @click="pinToTop($event, item)">置顶群聊</div>
              <!-- <div>消息免打扰</div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 创建群聊 -->
    <!-- <el-dialog class="dt-add-group" title="创建群聊" :visible.sync="addGroupIsShow" :append-to-body="true" width="560px" :show-close="false"
      :close-on-press-escape="false" :close-on-click-modal="false">
      <el-form :model="addGroupForm" :rules="addGroupRules" ref="addGroupValidateForm" label-position="left" label-width="82px" size="medium"
        @submit.native.prevent>
        <el-form-item label="群名称" prop="groupName">
          <el-input type="text" placeholder="请输入群名称" v-model="addGroupForm.groupName" maxlength="20" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" placeholder="请输入群简介" v-model="addGroupForm.briefIntroduction" rows="4" maxlength="500" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="群规设置" prop="groupRule">
          <el-switch v-model="addGroupForm.groupRuleSetting">
          </el-switch>
          <span class="dt-group-tip">开启群规设置后，所有群成员需同意群规才能进入群聊</span>
          <el-input v-show="addGroupForm.groupRuleSetting" type="textarea" placeholder="请输入群规则" v-model="addGroupForm.groupRule" rows="5"
            maxlength="500" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="submitFormAddGroup('addGroupValidateForm')"
          :loading="loading.addGroup">创建群聊</el-button><el-button class="dt-add-group-cancel" size="medium"
          @click="resetFormAddGroup('addGroupValidateForm')">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
/*  获取年月日时分秒 */
const getDateFormatString = function (type, timestamp) {
  var date = timestamp ? new Date(timestamp) : new Date(),
    dateStr = ''
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  var h = date.getHours()
  h = h < 10 ? '0' + h : h
  var min = date.getMinutes()
  min = min < 10 ? '0' + min : min
  var s = date.getSeconds()
  s = s < 10 ? '0' + s : s
  switch (type) {
    case 'md':
      dateStr = m + '-' + d
      break
    case 'mdhms':
      dateStr = m + '-' + d + ' ' + h + ':' + min + ':' + s
      break
    case 'ymd':
      dateStr = y + '-' + m + '-' + d
      break
    case 'ymdhms':
      dateStr = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s
      break
    default:
      dateStr = y + '' + m + '' + d + '' + h + '' + min + '' + s
      break
  }
  return dateStr
}
/* 获取格式化的时间戳（距离当前时间有多久） */
const getChatTimeString = function (timestamp) {
  var currDate = new Date(),
    currTimestamp = currDate.getTime(),
    timeLong = currTimestamp - timestamp,
    timeStr = ''
  if (timeLong <= 60 * 1000) {
    timeStr = '刚刚'
  } else if (timeLong > 60 * 1000 && timeLong <= 2 * 60 * 1000) {
    timeStr = '1分钟前'
  } else if (timeLong > 2 * 60 * 1000 && timeLong <= 60 * 60 * 1000) {
    var min = Math.floor(timeLong / 1000 / 60)
    timeStr = min + '分钟前'
  } else if (timeLong > 60 * 60 * 1000 && timeLong <= 24 * 60 * 60 * 1000) {
    var min = Math.floor(timeLong / 1000 / 60 / 60)
    timeStr = min + '小时前'
  } else if (timeLong > 24 * 60 * 60 * 1000) {
    var currYear = currDate.getFullYear(),
      timeYear = new Date(timestamp).getFullYear()
    if (currYear === timeYear) {
      //今年内
      timeStr = getDateFormatString('mdhms', timestamp)
    } else {
      //跨年
      timeStr = getDateFormatString('ymdhms', timestamp)
    }
  }
  return timeStr
}
export default {
  props: {
    id: {
      type: [String], // 可以是字符串
      required: true, // 必填项
      default: '0' // 如果没有传递，则使用默认值
    }
  },
  data() {
    return {
      uid: this.$tools.getDecrypt(this.$store.state.uid),
      // addGroupIsShow: false,
      // addGroupForm: {
      //   groupName: '',
      //   briefIntroduction: '',
      //   groupRule:
      //     '1.尊重法律：遵守国家法律法规，不发布违法信息。\n2.维护秩序：保持群内讨论积极健康，避免敏感和不当话题。\n3.保护隐私：不泄露公司或个人敏感信息。\n4.文明交流：使用礼貌用语，尊重他人，避免冲突。\n5.遵守纪律：群管理员有权管理群聊，违规者将受到警告或移除。',
      //   groupRuleSetting: true
      // },
      // addGroupRules: {
      //   groupName: [{ required: true, message: '请输入群名称', trigger: 'blur' }],
      //   groupRule: [{ required: true, message: '请设置群规', trigger: 'blur' }]
      // },
      GroupList: [],
      GroupListTop: [],
      GroupListBottom: [],
      messTypeUrl: [null, '/skb/img/chat-mess.png', '/skb/img/chat-sys.png', '/skb/img/ic_gjql.png'],
      // defaultProps: {
      //   children: 'children',
      //   label: 'groupName'
      // },
      loading: {
        groupList: true,
        addGroup: false
      },
      /***************消息提示*****************************/
      msgTime: 0,
      msgTitle: '数科帮网页版',
      msgTimer: null,
      groupName: '',
      currStep: -1
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    }
  },
  filters: {
    // filterPureUserName(val) {
    //   return val.length > 3 ? val.substring(0, 3) + '...' : val
    // },
    filterTimeStamp(val) {
      return getChatTimeString(new Date(val).getTime())
    }
    // filterMemberName(val) {
    //   return val.length > 7 ? val.substring(0, 7) + '...' : val
    // }
  },
  methods: {
    //获取新消息提示权限
    getNoticePermission() {
      if (window.Notification) {
        Notification.requestPermission()
      } else {
        console.log('浏览器不支持Notification')
      }
    },
    // addGroupMenu(command) {
    //   // console.log(command)
    //   if (command == '1') {
    //     this.addGroup()
    //   } else if (command == '2') {
    //     this.$router.push('/main/#/pc?tab=org&elTab=0')
    //   }
    // },
    // // 显示创建单一群聊输入框
    // addGroup() {
    //   this.addGroupIsShow = true
    // },
    // // 提交创建群聊
    // submitFormAddGroup(formName) {
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       this.loading.addGroup = true
    //       this.createGroup()
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },
    // 取消创建群聊 然后重置参数
    // resetFormAddGroup(formName) {
    //   this.$refs[formName].resetFields()
    //   this.addGroupIsShow = false
    //   this.addGroupForm.groupRuleSetting = true
    //   this.addGroupForm.groupRule =
    //     '1.尊重法律：遵守国家法律法规，不发布违法信息。\n2.维护秩序：保持群内讨论积极健康，避免敏感和不当话题。\n3.保护隐私：不泄露公司或个人敏感信息。\n4.文明交流：使用礼貌用语，尊重他人，避免冲突。\n5.遵守纪律：群管理员有权管理群聊，违规者将受到警告或移除。'
    // },
    // 发送创建单一群聊请求
    // createGroup() {
    //   var data = [
    //       {
    //         userId: this.uid,
    //         groupName: this.addGroupForm.groupName,
    //         briefIntroduction: this.addGroupForm.briefIntroduction,
    //         groupRule: this.addGroupForm.groupRule,
    //         groupRuleSetting: this.addGroupForm.groupRuleSetting ? 1 : 0
    //       }
    //     ],
    //     domain = [this.$store.state.DOMAIN],
    //     path = ['/project/customGroup/createSingleGroup'],
    //     dataAxios = this.$tools.getDataAxios(this, domain, path, data)
    //   Promise.all(dataAxios)
    //     .then((response) => {
    //       this.$tools.callbackAxios(this, response, (response) => {
    //         var data = response[0].data
    //         if (data.code === 200) {
    //           this.addGroupIsShow = false
    //           this.loading.addGroup = false
    //           this.$message({
    //             message: '创建成功',
    //             type: 'success',
    //             duration: 2000,
    //             onClose: () => {
    //               // this.chatListNoticeTop(data.data)
    //               // this.goGroupChat({ group_id: data.data.group_id })
    //               this.addGroupForm.groupName = ''
    //               this.addGroupForm.briefIntroduction = ''
    //               this.addGroupForm.groupRuleSetting = true
    //               this.addGroupForm.groupRule =
    //                 '1.尊重法律：遵守国家法律法规，不发布违法信息。\n2.维护秩序：保持群内讨论积极健康，避免敏感和不当话题。\n3.保护隐私：不泄露公司或个人敏感信息。\n4.文明交流：使用礼貌用语，尊重他人，避免冲突。\n5.遵守纪律：群管理员有权管理群聊，违规者将受到警告或移除。'
    //             }
    //           })
    //           this.$nextTick(() => {
    //             this.$socket.emit('leaveGroup', 'group-' + this.query.groupId)
    //             this.$router.push('/main/#/pc?tab=chat&groupId=' + data.data.groupId)
    //             this.$socket.emit('joinGroup', 'group-' + data.groupId)
    //           })
    //         } else {
    //           this.loading.addGroup = false
    //           this.$message({
    //             message: data.message,
    //             type: 'warning',
    //             duration: 2000,
    //             onClose: () => {}
    //           })
    //         }
    //       })
    //     })
    //     .catch((error) => {})
    // },
    //获取store 项目名称
    getStoreProjectName() {
      return this.$store.state.projectName ? JSON.parse(this.$store.state.projectName) : {}
    },
    //设置store 项目名称
    setStoreProjectName(projectId, projectName) {
      var storeProjectName = this.getStoreProjectName()
      storeProjectName[projectId] = projectName
      this.$store.commit('setProjectName', JSON.stringify(storeProjectName))
    },
    // 获取所有的群聊列表
    getGroupList() {
      var data = [
          {
            userId: this.uid,
            projectId: this.id
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/projectGroup/groupList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              // console.log(data, '-------')
              // // 使用forEach方法来给每个对象添加新属性
              // data.data.forEach((obj) => {
              //   obj.isShowTree = false // 给每个对象添加新属性
              // })
              // 使用forEach方法来给每个对象添加新属性
              data.data.topList.forEach((obj) => {
                // 是否显示右键菜单
                obj.isShowMenu = false
              })
              data.data.bottomList.forEach((obj) => {
                // 是否显示右键菜单
                obj.isShowMenu = false
              })
              this.GroupListTop = data.data.topList
              this.GroupListBottom = data.data.bottomList
              this.loading.groupList = false

              //设置项目名称 给标签用 等待高旭接口
              this.setStoreProjectName(data.data.projectId, data.data.projectName)
              this.$cookies.set('projectName', this.getStoreProjectName(), { path: '/', maxAge: 60 * 60 * 24 })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: 2000,
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //进入群聊
    goGroupChat(item) {
      this.$socket.emit('leaveGroup', 'group-' + this.query.groupId)
      this.$router.push('/main/#/pm?tab=detail&elTab=5&rootProjectId=' + item.rootProjectId + '&groupId=' + item.groupId, () => {
        //新手引导,跳转后等待dom加载完毕再进行回调
        if (this.currStep === 4) {
          var timer = setInterval(() => {
            if ($('.dt-chat-content-int .dt-icon-shenpi')[0]) {
              clearInterval(timer)
              this.$root.$emit('guide-to-5')
            }
          }, 50)
        }
      })
      this.$socket.emit('joinGroup', 'group-' + item.groupId)

      //获取通知权限 需要有交互才有提示
      this.getNoticePermission()
    },
    // handleNodeClick(data) {
    //   if (data.userInGroup == 1) {
    //     this.$socket.emit('leaveGroup', 'group-' + this.query.groupId)
    //     this.$router.push('/main/#/pc?tab=chat&groupId=' + data.groupId)
    //     this.$socket.emit('joinGroup', 'group-' + data.groupId)
    //   } else {
    //     return
    //   }
    // },
    // showTree(item) {
    //   var isShowTree = !item.isShowTree
    //   if (isShowTree) {
    //     var data = [
    //         {
    //           userId: this.uid,
    //           groupId: item.groupId
    //         }
    //       ],
    //       domain = [this.$store.state.DOMAIN],
    //       path = ['/project/customGroup/groupListSubTree'],
    //       dataAxios = this.$tools.getDataAxios(this, domain, path, data)
    //     Promise.all(dataAxios)
    //       .then((response) => {
    //         this.$tools.callbackAxios(this, response, (response) => {
    //           var data = response[0].data
    //           if (data.code === 200) {
    //             item.children = [data.data]
    //             item.isShowTree = !item.isShowTree
    //           } else {
    //             this.$message({
    //               message: data.message,
    //               type: 'warning',
    //               duration: 2000,
    //               onClose: () => {}
    //             })
    //           }
    //         })
    //       })
    //       .catch((error) => {})
    //   } else {
    //     item.children = []
    //     if (item.children.length == 0) {
    //       item.isShowTree = !item.isShowTree
    //     }
    //   }
    // },
    // 新建的群聊往数组的头部插入让他显示在最上面
    // chatListNoticeTop(data) {
    //   this.GroupList.forEach((item, index) => {
    //     if (item.groupId == data.groupId) {
    //       item.shortMessage = data.shortMessage
    //       item.createTimestamp = data.createTimestamp
    //       item.unreadCount = data.unreadCount
    //     }
    //   })
    //   let _index = this.GroupList.findIndex((obj) => obj.groupId === data.groupId)
    //   // 检查是否找到了对象，并输出结果
    //   if (_index === -1) {
    //     this.GroupList.unshift(data)
    //   } else {
    //     var _item = this.GroupList.splice(_index, 1)
    //     this.GroupList.unshift(_item[0])
    //   }
    // },
    // 删除群聊
    // deleteCustomGroup(data) {
    //   var _index = this.GroupList.findIndex((obj) => obj.groupId === data.groupId)

    //   if (_index == -1) {
    //     this.getGroupList()
    //   } else {
    //     // 检查是否找到了对象，并输出结果
    //     var _item = this.GroupList.splice(_index, 1)
    //   }
    //   this.$router.push('/main/#/pc?tab=chat')
    // },

    /**********************消息提示title和Notification***********************************/
    showMsg() {
      var title = this.msgTitle.replace('', '').replace('【您有新消息】', '')
      clearTimeout(this.msgTimer)
      this.msgTimer = setTimeout(() => {
        this.msgTime++
        this.showMsg()
        if (this.msgTime % 2 == 0) {
          document.title = '【您有新消息】' + title
        } else {
          document.title = title
        }
      }, 500)
      return [this.msgTimer, this.msgTitle]
    },
    clearMsg() {
      clearTimeout(this.msgTimer)
      document.title = this.msgTitle
    },
    setFocus() {
      if (!document.hidden) {
        this.clearMsg() //当前页面，停止提示
      }
    },
    popNotice() {
      //每个群同一时刻最多有一个通知
      this.$push.create('数科帮网页版', {
        tag: 'group_chat_' + this.query.groupId, //加上tag一个群一次最多只有一个通知 第二个覆盖第一个 第三个以后不通知了 关闭了才重新推送
        body: '收到 ' + this.groupName + ' 新消息',
        icon: '/skb/img/logo.png',
        requireInteraction: true,
        onClick: function () {
          window.focus()
          this.close()
        }
      })
    },
    /**
     * 右键置顶
     */
    rightToTop(e, item, index) {
      e.preventDefault() // 阻止默认的右键菜单
      this.$nextTick(() => {
        this.GroupListTop.forEach((item) => {
          item.isShowMenu = false
        })
        this.GroupListBottom.forEach((item) => {
          item.isShowMenu = false
        })
        // 设置菜单的位置
        item.isShowMenu = true
        const refList = this.$refs[item.groupId + '-' + index]
        if (!refList || refList.length === 0) {
          console.error('No elements found for ref:', item.groupId)
          return
        }
        var menuNode = refList[0].querySelector('.contextMenu')
        if (!menuNode) {
          console.error('No contextMenu found within ref:', item.groupId)
          return
        }
        // 使用requestAnimationFrame确保在下次重绘之前获取高度
        requestAnimationFrame(() => {
          // console.log(menuNode.offsetHeight) // 现在应该能获取到正确的高度
          // 视口高度
          const viewportHeight = window.innerHeight
          // 获取鼠标点击位置相对于视口的坐标
          const clientX = e.clientX
          const clientY = e.clientY
          // 获取div的偏移量
          const rect = refList[0].getBoundingClientRect()
          const offsetX = clientX - rect.left
          const offsetY = clientY - rect.top
          if (offsetX + 120 > 260) {
            menuNode.style.left = offsetX - 122 + 'px'
          } else {
            menuNode.style.left = offsetX + 2 + 'px'
          }
          if (clientY + menuNode.offsetHeight > viewportHeight) {
            menuNode.style.top = offsetY - menuNode.offsetHeight + 'px'
          } else {
            menuNode.style.top = offsetY + 2 + 'px'
          }
        })
      })
    },
    /**
     * 置顶函数
     */
    pinToTop(e, item) {
      e.stopPropagation()
      var data = [
          {
            userId: this.uid,
            type: item.toTop == 0 ? 1 : 0,
            groupId: item.groupId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/projectGroup/groupToTop'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              item.isShowMenu = false
              this.$message({
                message: data.message,
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: 2000,
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    // 定义一个函数来处理群聊信息更新
    updateGroupInfo(_data, groupList) {
      var _index = -1
      // var isAdvancedGroup = _data.noticeType === 3
      // 根据群聊类型查找索引
      _index = groupList.findIndex((obj) => obj.groupId === _data.groupId)
      if (_index == -1) {
        // 如果群聊不在列表中，根据类型添加到列表
        groupList.unshift(_data)
      } else {
        this.updateNormalGroupInfo(_data, _index, groupList)
      }
    },

    // 更新普通群聊信息
    updateNormalGroupInfo(_data, index, groupList) {
      // 根据未读消息数调整群聊位置
      if (_data.unreadCount > 0) {
        groupList.splice(index, 1)
        groupList.unshift(_data)
      } else if (_data.reSort === 1) {
        groupList.splice(index, 1)
        groupList.unshift(_data)
      } else {
        groupList.splice(index, 1, _data)
      }
    },

    //置顶或者取消置顶之后更新列表
    updateGroupList(_data) {
      if (_data.toTop == 0) {
        this.getGroupList()
        // var _index = this.GroupListTop.findIndex((obj) => obj.groupId === _data.groupId)
        // var _item = this.GroupListTop.splice(_index, 1)
        // _item[0].toTop = _data.toTop
        // this.GroupListBottom.unshift(_item[0])
      } else {
        var _index = this.GroupListBottom.findIndex((obj) => obj.groupId === _data.groupId)
        var _item = this.GroupListBottom.splice(_index, 1)
        _item[0].toTop = _data.toTop
        this.GroupListTop.unshift(_item[0])
      }
    },
    //处理文字给表情添加字号
    getemojiText(str) {
      // console.log(str)
      if (str) {
        const regex =
          /(\uD83D\uDE03|\u270A|\uD83D\uDE04|\uD83D\uDE01|\uD83D\uDE06|\uD83D\uDE05|\uD83E\uDD23|\uD83D\uDE02|\uD83D\uDE42|\uD83D\uDE09|\uD83D\uDE0A|\uD83D\uDE07|\uD83D\uDE15|\uD83D\uDE1F|\uD83D\uDE2E|\uD83D\uDE32|\uD83E\uDD7A|\uD83D\uDE26|\uD83D\uDE28|\uD83D\uDE2D|\uD83D\uDE31|\uD83D\uDE23|\uD83D\uDE1E|\uD83D\uDE29|\uD83D\uDE24|\uD83D\uDE21|\uD83D\uDE20|\uD83D\uDE0D|\uD83D\uDE18|\uD83D\uDE1C|\uD83E\uDD2A|\uD83E\uDD2D|\uD83E\uDD2B|\uD83E\uDD14|\uD83D\uDE11|\uD83D\uDE2A|\uD83D\uDE37|\uD83E\uDD2E|\uD83E\uDD27|\uD83D\uDE35|\uD83D\uDE0E|\uD83D\uDCA9|\uD83E\uDD16|\uD83D\uDE48|\uD83D\uDE49|\uD83D\uDE4A|\uD83D\uDC96|\uD83D\uDC94|\uD83D\uDC8B|\uD83D\uDCAF|\uD83D\uDCA2|\uD83D\uDCA8|\uD83D\uDCA4|\uD83D\uDD90|\uD83D\uDC4C|\uD83E\uDD1F|\uD83E\uDD19|\uD83D\uDC48|\uD83D\uDC49|\uD83D\uDC46|\uD83D\uDC47|\uD83D\uDC4D|\uD83D\uDC4F|\uD83D\uDE4C|\uD83E\uDD1D|\uD83D\uDE4F|\uD83D\uDC44|\uD83C\uDF49|\uD83E\uDDC0|\uD83C\uDF54|\uD83C\uDF5A|\uD83C\uDF75|\uD83C\uDF7A|\uD83C\uDF7B|\uD83E\uDD42)/g
        str = str.replace(regex, '<em style="font-size:16px">$1</em>')
      }

      return str
    }
    // noDisturb = 0 未开启 1 已开启 消息免打扰功能
    // enableDoNotDisturb(e, item) {
    //   e.stopPropagation()
    //   item.noDisturb = item.noDisturb == 0 ? 1 : 0
    //   var data = [{ groupId: item.groupId, userId: this.uid, type: item.noDisturb }],
    //     domain = [this.$store.state.DOMAIN],
    //     path = ['/project/customGroup/groupNoDisturb'],
    //     dataAxios = this.$tools.getDataAxios(this, domain, path, data)
    //   Promise.all(dataAxios)
    //     .then((response) => {
    //       this.$tools.callbackAxios(this, response, (response) => {
    //         var data = response[0].data
    //         if (data.code === 200) {
    //           if (item.noDisturb == 1) {
    //             this.$message({
    //               message: '设置群聊免打扰成功',
    //               type: 'success',
    //               duration: 2000,
    //               onClose: () => {}
    //             })
    //           } else {
    //             this.$message({
    //               message: '取消群聊免打扰',
    //               type: 'info',
    //               duration: 2000,
    //               onClose: () => {}
    //             })
    //           }
    //         } else {
    //           this.$message({
    //             message: data.message,
    //             type: 'warning',
    //             duration: 2000,
    //             onClose: () => {}
    //           })
    //         }
    //       })
    //     })
    //     .catch((error) => {})
    // }
  },
  mounted() {
    this.getGroupList()
    this.$root.$on('guide-to-4', () => {
      this.currStep = 4
    })
    this.$root.$on('guide-to-close', () => {
      this.currStep = -1
    })
    this.$root.$on('guide-to-end', () => {
      this.currStep = -1
    })
    //浏览器切屏获得焦点
    $(document).on('visibilitychange', () => {
      this.setFocus()
    })
    var timer = setInterval(() => {
      if (this.$socket) {
        clearInterval(timer)
        this.$socket.on('project_group_unread', (data) => {
          var _data = JSON.parse(data)
          _data.isShowMenu = false
          if (_data.rootProjectId != this.query.rootProjectId) {
            console.log('项目id不一致')
            return
          }
          if (_data.toTop == 1) {
            this.updateGroupInfo(_data, this.GroupListTop)
          } else {
            this.updateGroupInfo(_data, this.GroupListBottom)
          }
          // var _index = this.GroupList.findIndex((obj) => obj.groupId === _data.groupId)
          // if (_index == -1) {
          //   if (_data.noticeType != 3) {
          //     this.GroupList.unshift(_data)
          //   } else {
          //     console.log('高级群聊')
          //   }
          // } else {
          //   if (_data.unreadCount > 0) {
          //     this.GroupList.splice(_index, 1)
          //     this.GroupList.unshift(_data)
          //   } else {
          //     if (_data.reSort == 1) {
          //       this.GroupList.splice(_index, 1)
          //       this.GroupList.unshift(_data)
          //     } else {
          //       this.GroupList.splice(_index, 1, _data)
          //     }
          //     // this.GroupList.splice(_index, 1, _data)
          //   }
          // }
          // if (_data.noticeType === 2 && _data.unreadCount > 0) {
          //   //系统通知且未读数大于0
          //   if (document.hidden) {
          //     //非当前页
          //     this.showMsg() //新消息闪烁
          //     this.popNotice() //系统提示
          //   }
          // }
        })
        this.$socket.on('project_group_change', (data) => {
          var _data = JSON.parse(data)
          if (_data.rootProjectId == this.query.rootProjectId) {
            this.getGroupList()
          }
        })
        this.$socket.on('project_group_totop', (data) => {
          var _data = JSON.parse(data)
          if (_data.rootProjectId != this.query.rootProjectId) {
            console.log('项目id不一致')
            return
          }
          this.updateGroupList(_data)
        })
      }
    }, 10)
    $(document).on('click contextmenu', () => {
      this.GroupListTop.forEach((item) => {
        item.isShowMenu = false
      })
      this.GroupListBottom.forEach((item) => {
        item.isShowMenu = false
      })
    })
  }
}
</script>
<style scoped>
.dt-chat-groups {
  flex: 1;
}
.dt-groups-loading {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.dt-groups-loading span {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}
.dt-groups-title i:hover {
  color: #2f54eb;
}
/* 添加单一群聊弹窗样式 */
.dt-add-group >>> .el-dialog__footer {
  border-top: 1px solid #ecf0f8;
  padding: 14px 20px;
}
.dt-add-group >>> .el-dialog__body {
  padding-top: 10px;
  padding-bottom: 0px;
}
.dt-add-group >>> .el-textarea {
  padding-bottom: 20px;
  border: 1px solid #dcdfe6;
}
.dt-add-group >>> .el-textarea__inner {
  border: none;
  resize: none;
}
.dt-add-group >>> .el-input__count {
  right: 5px;
  bottom: 3px;
  background: none;
}
.dt-add-group >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::after {
  content: '*';
  color: #f56c6c;
  margin-left: 4px;
}
.dt-add-group >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: '';
  color: #f56c6c;
  margin-right: 0px;
}
.dt-group-tip {
  margin: 2px 0px 0px 8px;
  font-size: 12px;
  color: #606262;
}
/* 添加单一群聊弹窗样式 */
/* 群聊列表样式 */
/* .dt-list-items {
  display: flex;
  flex-direction: column;
  overflow: auto;
} */
.dt-list-item {
  height: 38px;
  padding: 11px 16px;
  display: flex;
  cursor: pointer;
  position: relative;
}
.dt-list-item-topicon {
  position: absolute;
  top: 30px;
  left: 38px;
  margin-right: 0px !important;
}
.dt-list-item:hover {
  background-color: #f5f8ff;
}
.dt-list-item.on {
  background-color: #f0f5ff;
}
.dt-list-item img {
  margin-right: 8px;
}
.dt-item-des {
  margin-top: 2px;
  flex: 1;
}
.dt-des-chatname {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.dt-des-chatname span {
  color: #1f1f1f;
  display: block;
  width: 109px;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 16px;
  white-space: nowrap;
}
.dt-des-chatname i {
  font-size: 11px;
  color: rgb(192, 196, 204);
  white-space: nowrap;
}
.dt-des-chattip {
  display: flex;
  justify-content: space-between;
}
.dt-des-chattip .dt-des-markdup {
  font-size: 12px;
  color: #909399;
  width: 130px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  /* height: 15px; */
}
.dt-des-chattip em {
  font-size: 10px;
  color: #fff;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 9px;
  background-color: #ff4d4f;
}
.dt-chat-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}
/* 群聊列表样式 */
/* 高级群聊列表样式 */
.dt-list-item-gj {
  height: 60px;
  padding: 11px 16px;
  display: flex;
  cursor: pointer;
  align-items: center;
  background-color: #fffaf0;
  box-sizing: border-box;
}
.dt-list-item-gj img {
  margin-right: 8px;
}
.dt-list-item-gj-name {
  flex: 1;
  /* line-height: 20px; */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.dt-list-item-gj-unreadCount em {
  font-size: 10px;
  color: #fff;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 9px;
  background-color: #ff4d4f;
  display: inline-block;
}
.dt-list-gj-content {
  /* width: 280px; */
  overflow: auto;
}
::v-deep .custom-tree-node {
  color: #1f1f1f;
}
::v-deep .custom-tree-node[disabled='disabled'] {
  color: #909399;
  cursor: not-allowed;
}
::v-deep .custom-tree-node {
  display: flex;
  justify-content: space-between;
  flex: 1;
  padding-right: 16px;
  align-items: center;
  /* height: 100%;
  line-height: 36px; */
}
/* ::v-deep .custom-tree-node :hover {
  background-color: #f5f7fa;
} */
.dt-list-gj-content >>> .el-tree-node__content {
  height: 36px;
}
.dt-list-gj-content >>> .el-tree-node__children {
  overflow: visible;
}

/* 选择包含至少一个 .custom-tree-node 子元素的父元素 */
.dt-list-gj-content >>> .el-tree-node__content:has(.custom-tree-node[disabled='disabled']) {
  /* 应用样式 */
  cursor: not-allowed;
}
/* .dt-list-gj-content >>> .el-tree-node__content::-webkit-scrollbar {
  display: none; 
}
.dt-list-gj-content >>> .el-tree-node__content {
  scrollbar-width: none; 
  -ms-overflow-style: none; 
} */
/* .dt-list-gj-content >>> .el-tree div[aria-expanded='true'] .el-tree-node__content {
  background-color: red;
} */
/* .dt-list-gj-content >>> .el-tree {
  overflow: auto;
} */
/* .dt-list-gj-content >>> .el-tree-node__children {
  overflow: auto;
} */

/* 高级群聊列表样式 */
/* 右键菜单样式 */
.contextMenu {
  width: 120px;
  /* height: 72px; */
  background: #ffffff;
  border: 1px solid;
  border-color: #e9eef7;
  border-radius: 4px;
  box-shadow: 0px 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  box-sizing: border-box;
  padding: 4px 1px;
  position: absolute;
}
.contextMenu div {
  height: 31px;
  /* text-align: center; */
  line-height: 31px;
  padding-left: 16px;
}
.contextMenu div:hover {
  background: #f0f5ff;
}
</style>
